#!/bin/sh

# Please edit /opt/etc/tv_grab_wl500g_info.cfg first!
# Place desired channel id's there, one number per line.
# You may see channel id list by running tv_grab_wl500g_info --configure

IDLIST="/opt/etc/tv_grab_wl500g_info.cfg"
XMLTV_FILE="/opt/tmp/xmltv"
XMLTV_SRC="http://www.teleguide.info/download/new3/xmltv.xml.gz"
SEDCMD="/bin/sed"
WGETCMD="/usr/bin/wget"
GZIPCMD="/bin/gunzip"


GetXmltv () {

    $WGETCMD -q -O - $XMLTV_SRC | $GZIPCMD > $XMLTV_FILE
    [ -e "$XMLTV_FILE" ] || exit 1;

}


case $1 in

    "--configure")
        GetXmltv
        $SEDCMD -n '/<channel/p;/<display-name/p' $XMLTV_FILE
        rm -f $XMLTV_FILE
    ;;
    "--version")
        echo "This is a tv_grab_wl500g_info v.0.1 grabber"
        echo "for russian www.teleguide.info site. Made by wl500g.info community."
    ;;
    "--description")
        echo "teleguide.info grabber by wl500g.info community"
    ;;
    "--capabilities")
        echo "teleguide.info"
    ;;
    *)
        GetXmltv

        printf "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE tv SYSTEM \"xmltv.dtd\">\n<tv>\n"

        while read chanid
        do

            $SEDCMD -n -e "
                /id=\"${chanid}\"/,/<\/channel\>/p
                /channel=\"${chanid}\"/,/programme\>/{
                /<[/]\{0,1\}programme/{
                p
                b end
                }
                /<[/]\{0,1\}title/{
                p
                b end
                }
                b end
                }
                :end
            " $XMLTV_FILE

        done < $IDLIST

        printf "</tv>\n"

        rm -f $XMLTV_FILE

    ;;

esac


exit 0;
